var moment = require('moment')
  , _ = require('underscore')
var format = module.exports = {
  stampToTime:function(value){
    var millios = (value.toString().length>10?1:1000);
    return moment(value*millios).format('YYYY-MM-DD HH:mm')
  },
  rate:function(value){
    var v = parseFloat(value)
    if(isNaN(v)||!v){
        return '0.00%';
    }
    return (v*100).toFixed(2)+'%';
  },
  numberic:function(v){
    var med,
        tmp_value,
        out_value = parseFloat(v);
    if (isNaN(out_value)||out_value===0) {
        return "0.00";
    }
    med = 0;
    do{
        med += 2;
        tmp_value = out_value.toFixed(med);
    }while(parseFloat(tmp_value)===0&&med<6);
    out_value = tmp_value
    return out_value.toString().replace(/(\d{1,3})(?=(\d{3})+(?:\.))/g, "$1,");
  },
  integer:function(v){
    var out_value = parseInt(v);
    if (isNaN(out_value)) {
        return "0";
    }
    return out_value.toString().replace(/(\d{1,3})(?=(\d{3})+(?:$|\.))/g, "$1,");
  },
  duration:function(v,d){
    d = d || (new Date()).getTime();
    return moment.duration(d-v).humanize()+'之前'
  },
  qDuration:function(v,d){
    d = d || (new Date()).getTime();
    return Math.ceil(moment.duration(d-v).asSeconds())+'秒之前'
  },
  dataSize:function(v){
    var bits = (v).toString().replace(/\.\d+/,'');
    var units = ['B','KB','MB','GB','TB'];
    var i;
    for(i=units.length-1;i+1;i--){
      if(bits>=Math.pow(2,i*10)){
        return format.numberic(v/Math.pow(2,i*10)) + ' '+units[i]
      }
    }
    return format.numberic(v) + ' B'
  },
  kSize:function(v){
    var bits = (v).toString().replace(/\.\d+/,'').length;
    var units = ['','K','M','G','T','P','E','Z','Y'];
    var i;
    for(i=units.length-1;i+1;i--){
      if(bits>i*3){
        return format.numberic(v/Math.pow(10,i*3)) + ' '+units[i]
      }
    }
    return format.numberic(v)
  },
  numSecond:function(v){
    if(v>1){
      return format.numberic(v) +' s'
    }else{
      return (v*1000).toFixed(0)+' ms'
    }
  },
  numSecond2: function(v){
    if(v>1){
      return format.numberic(v) +' s';
    }else{
      return (v*1000).toFixed(2)+' ms';
    }
  },
  round:function(item) {
     if (isNaN(item)) {
        return 0;
    }else{
      return Math.round(item)
    }
  },
  shortTitle:function(title,num) {
    if(title==undefined||title==null||num<0){
      return title
    }

    if(title.length>num){
      return title .substring(0,num)+'...';
    }else{
        return title;
    }
  },
  numSecs: function(v) {
    //Math.round
    if (v < 1000) {
      return format.round(v) + ' ms'

    } else if (v >= 1000 && v < 1000 * 60) {
      return format.numberic(v / 1000) + ' s'
    } else {
      return format.numberic(v / (1000 * 60)) + ' min'
    }
  }
}
